package com.yss.reportworld.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yss.common.core.domain.YssResponse;
import com.yss.common.core.enums.YssStatusEnum;
import com.yss.common.core.utils.StringUtils;
import com.yss.common.core.utils.easyexecl.EasyExeclUtil;
import com.yss.common.security.annotation.InnerAuth;
import com.yss.common.security.annotation.Logical;
import com.yss.reportworld.domain.Database;
import com.yss.reportworld.service.*;
import com.yss.system.api.domain.SysDictData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.yss.common.logger.annotation.Log;
import com.yss.common.logger.enums.BusinessType;
import com.yss.common.security.annotation.RequiresPermissions;
import com.yss.reportworld.domain.DatabaseCheck;
import com.yss.common.core.web.controller.BaseController;
import com.yss.common.core.web.domain.AjaxResult;
import com.yss.common.core.web.page.TableDataInfo;

/**
 * 校验语句信息Controller
 *
 * @author yss
 * @date 2023-03-31
 */
@RestController
@RequestMapping("/databaseCheck")
public class DatabaseCheckController extends BaseController {
    @Autowired
    private IDatabaseCheckService databaseCheckService;
    @Autowired
    private IDatabaseService databaseService;
    @Autowired
    private ISqlScriptService sqlScriptService;
    @Autowired
    private IDescriptionService descriptionService;
    @Autowired
    private IWeComService weComService;

    /**
     * 查询校验语句信息列表
     */
    @RequiresPermissions("reportworld:databaseCheck:list")
    @GetMapping("/list")
    public TableDataInfo list(DatabaseCheck databaseCheck) {
        startPage();
        List<DatabaseCheck> list = databaseCheckService.selectDatabaseCheckList(databaseCheck);
        return getDataTable(list);
    }

    /**
     * 导出校验语句信息列表
     */
    @RequiresPermissions("reportworld:databaseCheck:export")
    @Log(title = "校验语句信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DatabaseCheck databaseCheck) {
        List<DatabaseCheck> list = databaseCheckService.selectDatabaseCheckList(databaseCheck);
        EasyExeclUtil.export(response, list, DatabaseCheck.class);
    }

    /**
     * 初始化 加载
     */
    @RequiresPermissions("reportworld:databaseCheck:list")
    @Log(title = "校验语句信息", businessType = BusinessType.OTHER)
    @PostMapping("/init")
    public AjaxResult init(@RequestBody DatabaseCheck databaseCheck) {
        AjaxResult ajax = AjaxResult.success();
        QueryWrapper<Database> wrapper = new QueryWrapper<>();
        wrapper.eq("STATUS", YssStatusEnum.NORMAL.getCode());
        wrapper.like("CODE", "RW_DB_");
        wrapper.orderByAsc("CODE");
        ajax.put("tables", databaseService.list(wrapper));
        ajax.put("hisVersions", sqlScriptService.getReductionVersion(false));
        return ajax;
    }

    /**
     * 获取校验语句信息详细信息
     */
    @RequiresPermissions("reportworld:databaseCheck:query")
    @Log(title = "校验语句信息", businessType = BusinessType.OTHER)
    @PostMapping(value = "/getCheck")
    public AjaxResult getCheck(@RequestBody DatabaseCheck databaseCheck) {
        return success(databaseCheckService.selectDatabaseCheckById(databaseCheck));
    }

    /**
     * 新增校验语句信息
     */
    @RequiresPermissions("reportworld:databaseCheck:add")
    @Log(title = "校验语句信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody @Validated DatabaseCheck databaseCheck) {
        databaseCheckService.addDatabaseCheck(databaseCheck);
        return success();
    }

    /**
     * 修改校验语句信息
     */
    @RequiresPermissions("reportworld:databaseCheck:edit")
    @Log(title = "校验语句信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody @Validated DatabaseCheck databaseCheck) {
        databaseCheckService.editDatabaseCheck(databaseCheck);
        return success();
    }

    /**
     * 删除校验语句信息
     */
    @RequiresPermissions("reportworld:databaseCheck:remove")
    @Log(title = "校验语句信息", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    public AjaxResult remove(@RequestBody DatabaseCheck databaseCheck) {
        databaseCheckService.delDatabaseCheck(databaseCheck);
        return success();
    }

    /**
     * 保存表顺序信息
     */
    @RequiresPermissions("reportworld:databaseCheck:orderNum")
    @Log(title = "校验语句信息", businessType = BusinessType.UPDATE)
    @PostMapping("/handleUpdateOrderNum")
    public AjaxResult handleUpdateOrderNum(@RequestBody String josn) {
        List<DatabaseCheck> list = JSONArray.parseArray(josn, DatabaseCheck.class);
        if (StringUtils.isNotEmpty(list)) {
            databaseCheckService.handleUpdateOrderNum(list);
        }
        return success();
    }


    /**
     * 更新校验语句
     */
    @RequiresPermissions("reportworld:databaseCheck:data:checkSql")
    @PostMapping(value = "/databaseDataCheckSql")
    public AjaxResult databaseDataCheckSql(@RequestBody DatabaseCheck databaseCheck) {
        AjaxResult ajax = AjaxResult.success();
        databaseCheckService.updateCheckDataBase(databaseCheck);
        return ajax;
    }


    /**
     * 数据校验 ，导出ZIP也需要检验的权限
     */
    @RequiresPermissions(value = {"reportworld:databaseCheck:data:check", "reportworld:upgradetoolszip"}, logical = Logical.OR)
    @PostMapping(value = "/databaseDataCheck")
    public AjaxResult databaseDataCheck(@RequestBody DatabaseCheck databaseCheck) {
        AjaxResult ajax = AjaxResult.success();
        databaseCheck.setCheckPass(true);
        String msgInfo = databaseCheckService.queryCheckDataBaseInfoAll(databaseCheck);
        ajax.put("msgInfo", msgInfo);
        if (!databaseCheck.getCheckPass()) {
            ajax.put("result", false);
        }
        return ajax;
    }

    /**
     * 定时任务调用检查数据
     *
     * @return
     */
    @InnerAuth
    @GetMapping("/queryCheckDataBaseInfoAll")
    public YssResponse<String> queryCheckDataBaseInfoAll() {
        List<SysDictData> dicvalueList = sqlScriptService.getReductionVersion(true);
        // 获取所有备份的数据，每个版本检查
        StringBuffer buffer = new StringBuffer();
        for (SysDictData sysDictData : dicvalueList) {
            DatabaseCheck databaseCheck = new DatabaseCheck();
            databaseCheck.setHisVersion(sysDictData.getDictValue());
            buffer.append(databaseCheckService.queryCheckDataBaseInfoAll(databaseCheck));
        }
        // 发送企业微信
        if (StringUtils.isNotEmpty(buffer.toString())) {
            weComService.sendMessageToManage(buffer.toString());
        }
        // 基础数据的策略和备份信息检查，没有就提示
        String msgInfo = descriptionService.queryCheckInfo();
        if (StringUtils.isNotEmpty(msgInfo)) {
            weComService.sendMessageToManage(msgInfo);
        }
        return YssResponse.ok(buffer.toString());
    }
}
